//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.tuliu.appupdate.updatelib;

import android.content.Context;
import android.text.TextUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

/**
 * @author liaoyong
 * @desc 功能描述
 * @date 2016/4/11 13:57
 */
public class HttpHelper {
    private static final int HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    private static final boolean IS_DEBUG = false;
    private static final int DEFAULT_TIMEOUT = 60000;

    public HttpHelper() {
    }

    private static HttpURLConnection getUrlConnection(String requestUrl) {
        URL url;
        try {
            url = new URL(requestUrl);
        } catch (MalformedURLException var5) {
            return null;
        }

        try {
            Proxy e = getProxy();
            HttpURLConnection conn;
            if(e != null) {
                conn = (HttpURLConnection)url.openConnection(e);
            } else {
                conn = (HttpURLConnection)url.openConnection();
            }

            conn.setConnectTimeout('\uea60');
            conn.setReadTimeout('\uea60');
            conn.setRequestProperty("Accept-Encoding", "gzip");
            conn.setInstanceFollowRedirects(true);
            if(conn.getRequestProperty("User-Agent") == null) {
                conn.addRequestProperty("User-Agent", System.getProperty("http.agent"));
            }

            return conn;
        } catch (IOException var4) {
            return null;
        }
    }

    static String getReslUrl(Context context, String requestUrl) {
        HttpURLConnection conn = getUrlConnection(requestUrl);
        if(conn != null) {
            conn.setInstanceFollowRedirects(false);

            int responseCode;
            try {
                responseCode = conn.getResponseCode();
            } catch (IOException var5) {
                return null;
            }

            if(302 != responseCode) {
                return requestUrl;
            } else {
                String location = conn.getHeaderField("Location");
                return TextUtils.isEmpty(location)?requestUrl:location;
            }
        } else {
            return null;
        }
    }

    /**
     * 发送GET请求
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static HttpURLConnection sendGetRequest(String url,
                                               Map<String, String> params, Map<String, String> headers)
            throws Exception {
        StringBuilder buf = new StringBuilder(url);
        Set<Map.Entry<String, String>> entrys = null;
        // 如果是GET请求，则请求参数在URL中
        if (params != null && !params.isEmpty()) {
            buf.append("?");
            entrys = params.entrySet();
            for (Map.Entry<String, String> entry : entrys) {
                buf.append(entry.getKey()).append("=")
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                        .append("&");
            }
            buf.deleteCharAt(buf.length() - 1);
        }
        URL url1 = new URL(buf.toString());
        HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
        conn.setRequestMethod("GET");
        // 设置请求头
        if (headers != null && !headers.isEmpty()) {
            entrys = headers.entrySet();
            for (Map.Entry<String, String> entry : entrys) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        conn.getResponseCode();
        return conn;
    }

    /**
     * 发送POST请求
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static HttpURLConnection sendPostRequest(String url,
                                                Map<String, String> params, Map<String, String> headers)
            throws Exception {
        StringBuilder buf = new StringBuilder();
        Set<Map.Entry<String, String>> entrys = null;
        // 如果存在参数，则放在HTTP请求体，形如name=aaa&age=10
        if (params != null && !params.isEmpty()) {
            entrys = params.entrySet();
            for (Map.Entry<String, String> entry : entrys) {
                buf.append(entry.getKey()).append("=")
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                        .append("&");
            }
            buf.deleteCharAt(buf.length() - 1);
        }
        URL url1 = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        OutputStream out = conn.getOutputStream();
        out.write(buf.toString().getBytes("UTF-8"));
        if (headers != null && !headers.isEmpty()) {
            entrys = headers.entrySet();
            for (Map.Entry<String, String> entry : entrys) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        conn.getResponseCode(); // 为了发送成功
        return conn;
    }
    public static String get(Context context, String requestUrl) {
        String[] strings = requestUrl.split("\\?");
        if (strings == null || strings.length != 2)
            return null;

        Map<String, String> paramMap = new HashMap<String, String>();
        String[] pairs = strings[1].split("&");
        for (int i=0;i<pairs.length;i++) {
            String pair = pairs[i];
            String[] keyValue = pair.split("=");
            paramMap.put(keyValue[0], keyValue[1]);
        }
        HttpURLConnection conn = null;
        try {
            conn = sendGetRequest(strings[0], paramMap, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(conn != null) {
            try {
                int responseCode = conn.getResponseCode();
                if(200 != responseCode) {
                    throw new IOException("The status code of http is not SC_OK(200):" + responseCode + ",\r\n\turl=" + requestUrl);
                } else {
                    Object e = conn.getInputStream();
                    String encoding = conn.getContentEncoding();
                    encoding = encoding == null?"UTF-8":encoding;
                    if(encoding.contains("gzip")) {
                        e = new GZIPInputStream((InputStream)e);
                    }

                    return IOUtils.toString((InputStream)e, conn.getRequestProperty("charset"));
                }
            } catch (IOException var6) {
                return null;
            }
        } else {
            return null;
        }
    }

    public static String get(Context context, String requestUrl, File dstFile, ProgressListener listener) {
        HttpURLConnection conn = getUrlConnection(requestUrl);
        if(listener != null) {
            listener.onProgressChanged(0L, 100L);
        }

        if(conn != null) {
            if(dstFile != null && dstFile.exists() && dstFile.isFile() && dstFile.length() > 0L) {
                conn.addRequestProperty("RANGE", "bytes=" + dstFile.length() + "-");
            }

            try {
                int responseCode = conn.getResponseCode();
                if(responseCode == 416) {
                    if(dstFile != null) {
                        dstFile.delete();
                    }

                    responseCode = -1;
                    conn = getUrlConnection(requestUrl);
                    if(conn != null) {
                        responseCode = conn.getResponseCode();
                    }
                }

                if(responseCode != 200 && responseCode != 206) {
                    throw new IOException("The status code of http is not SC_OK(200) or PARTIAL_CONTENT(206):" + responseCode + ",\r\n\turl=" + requestUrl);
                }

                if(responseCode == 200 && dstFile != null) {
                    dstFile.delete();
                }

                transferData(conn, dstFile, listener);
                if(dstFile != null) {
                    return dstFile.getPath();
                }
            } catch (IOException var7) {
                return null;
            }
        }

        return null;
    }

    private static void transferData(HttpURLConnection conn, File dstFile, ProgressListener listener) throws IOException {
        boolean isApk = false;
        Map headers = conn.getHeaderFields();
        if(headers != null) {
            Iterator bin = headers.keySet().iterator();

            while(bin.hasNext()) {
                String bout = (String)bin.next();
                if(bout != null && bout.contains("text")) {
                    isApk = true;
                    break;
                }
            }
        }

        BufferedInputStream bin1 = null;
        BufferedOutputStream bout1 = null;

        try {
            long e = dstFile.exists()?dstFile.length():0L;
            long total = e + (long)conn.getContentLength();
            if(listener != null) {
                listener.onProgressChanged(e, total);
            }

            bout1 = new BufferedOutputStream(new FileOutputStream(dstFile, true));
            bin1 = new BufferedInputStream(conn.getInputStream());
            byte[] buffer = new byte[8192];

            int read;
            while((read = bin1.read(buffer)) != -1) {
                bout1.write(buffer, 0, read);
                e += (long)read;
                if(listener != null) {
                    listener.onProgressChanged(e, total);
                }
            }

            bout1.flush();
            if(isApk && dstFile.length() < 5120L) {
                throw new IOException("服务器返回的不是一个apk文件");
            }
        } finally {
            try {
                if(bout1 != null) {
                    bout1.flush();
                }
            } catch (IOException var32) {
                ;
            } finally {
                IOUtils.closeQuietly(bout1);
            }

            IOUtils.closeQuietly(bin1);
        }
    }

    private static Proxy getProxy() {
        String host = android.net.Proxy.getDefaultHost();
        int port = android.net.Proxy.getDefaultPort();
        if(!TextUtils.isEmpty(host) && port > 0) {
            InetSocketAddress sa = new InetSocketAddress(host, port);
            return new Proxy(Type.HTTP, sa);
        } else {
            return null;
        }
    }
}
